/* 1592. 重新排列单词间的空格 */
/**
 * @param {string} text
 * @return {string}
 */
var reorderSpaces = function (text) {
	const len = text.length
	let [spaceCount, textCount] = [0, 0]
	let result = []
	for (let i = 0; i < len; i++) {
		const curText = text.charAt(i)
		let j = i
		if (curText === ' ') {
			spaceCount++
		} else {
			while (text.charAt(j) !== ' ' && j < len) {
				j++
			}
			textCount++
			result.push(text.slice(i, j))
			i = j - 1
		}
	}
	const space = Math.floor(spaceCount / (textCount - 1))
	result = result
		.map((text, index) =>
			text.padEnd(
				text.length + (index !== textCount - 1 ? space : 0),
				' '
			)
		)
		.join('')
	result = result.padEnd(len, ' ')
	return result
}
var reorderSpaces = function (text) {
	const wordArr = text.split(' ').filter(Boolean) // 所有的单词数组
	const spaceCount = text.length - wordArr.join('').length // 所有的空格数

	// 如果单词长度=1，直接将空格拼接到单词末尾
	if (wordArr.length === 1)
		return spaceCount > 0 ? wordArr[0] + ' '.repeat(spaceCount) : text

	// 单词之间的空格数
	const spaceBetween = (spaceCount / (wordArr.length - 1)) | 0

	// 字符串末尾应该添加的空格数，
	// 注意不能用const tailSpace = spaceCount % spaceBetween，
	// 因为spaceBetween=1时，得到的结果永远为0
	const tailSpace = spaceCount - spaceBetween * (wordArr.length - 1)

	// 拼接我们需要返回的字符串主体
	let ans = wordArr.join(' '.repeat(spaceBetween))

	// 判断字符串末尾是否需要添加空格
	return tailSpace > 0 ? (ans += ' '.repeat(tailSpace)) : ans
}
const result = reorderSpaces('  this   is  a sentence ')
console.log('reorderSpaces :>>', result.length)
